 #include "vreceive.h"
#include "ui_vreceive.h"
#include "Tools/csettings.h"
#include "Tools/cconversion.h"
#include <QTextCharFormat>
#include <QTime>
#include "QDebug"
#include <cstring>

VReceive::VReceive(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::VReceive)
{
    ui->setupUi(this);

    ui->customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectAxes |
                                    QCP::iSelectLegend | QCP::iSelectPlottables);
    ui->customPlot->xAxis->setRange(-8, 8);
    ui->customPlot->yAxis->setRange(-5, 5);
    ui->customPlot->axisRect()->setupFullAxesBox();

    ui->customPlot->xAxis->setLabel("x Axis");
    ui->customPlot->yAxis->setLabel("y Axis");
    ui->customPlot->legend->setVisible(true);
    QFont legendFont = font();
    legendFont.setPointSize(10);
    ui->customPlot->legend->setFont(legendFont);
    ui->customPlot->legend->setSelectedFont(legendFont);
    ui->customPlot->legend->setSelectableParts(QCPLegend::spItems); // legend box shall not be selectable, only legend items

    ui->customPlot->rescaleAxes();

    connect(ui->customPlot, SIGNAL(selectionChangedByUser()), this, SLOT(selectionChanged()));
    connect(ui->customPlot, SIGNAL(mousePress(QMouseEvent*)), this, SLOT(mousePress()));
    connect(ui->customPlot, SIGNAL(mouseWheel(QWheelEvent*)), this, SLOT(mouseWheel()));
    connect(ui->customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), ui->customPlot->xAxis2, SLOT(setRange(QCPRange)));
    connect(ui->customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), ui->customPlot->yAxis2, SLOT(setRange(QCPRange)));
    connect(ui->customPlot, SIGNAL(axisDoubleClick(QCPAxis*,QCPAxis::SelectablePart,QMouseEvent*)), this, SLOT(axisLabelDoubleClick(QCPAxis*,QCPAxis::SelectablePart)));
    connect(ui->customPlot, SIGNAL(legendDoubleClick(QCPLegend*,QCPAbstractLegendItem*,QMouseEvent*)), this, SLOT(legendDoubleClick(QCPLegend*,QCPAbstractLegendItem*)));
    //链接信号
    connect(this,&VReceive::itermchanged,[=](int nIterm){
        this->itermchange(nIterm);
    });


    ui->customPlot->installEventFilter(this);

    // ui->pushButton_hex->setProperty("iconText",true);
    // ui->pushButton_hex->setText(QChar(0xe604));

    // ui->pushButton_timestamp->setProperty("iconText",true);
    // ui->pushButton_timestamp->setText(QChar(0xe6b5));


    // ui->pushButton_stop->setProperty("iconText",true);
    // ui->pushButton_stop->setText(QChar(0xe6a6));

    // ui->pushButton_clear->setProperty("iconText",true);
    // ui->pushButton_clear->setText(QChar(0xe7d4));

    //this->setStyleSheet(""); //@NOTE 可以解决初始化按钮不显示图标的问题



}

VReceive::~VReceive()
{
    delete ui;
}

void VReceive::setConnectionProxy(CUdp *pConnectManager)
{
    m_pConnect = pConnectManager;
    connect(m_pConnect,&CUdp::sigStateChanged,[=](CUdp::EnmState enmState){
        this->stateChanged(enmState);
    });
    connect(m_pConnect,&CUdp::sigConnectChanged,[=](QString strIp,quint16 nPort,bool bState){
        this->connectStateChanged(strIp,nPort,bState);
    });
    connect(m_pConnect,&CUdp::sigDataArrive,[=](QString strIp,quint16 nPort,QByteArray byteArr){
        this->dataArrive(strIp,nPort,byteArr);
       /* if(ui->chart->isEnabled())*/
    });
}

void VReceive::dataArrive(QString strIp, quint16 nPort, QByteArray byteArr)
{
    Q_UNUSED(strIp)
    Q_UNUSED(nPort)
    if(!m_pConnect->m_pUdp->isOpen())
    {
        // qDebug()<< "is not open ";
        return ;
    }
    // qDebug()<< "dataArrive: "<<byteArr;
    if(ui->pushButton_stop->isChecked()) //停止显示
    {
        // qDebug()<< "stop display: ";
        return ;
    }
    //转换文本
    QString strText;
    if(ui->pushButton_hex->isChecked()){
        strText = CConversion::byteArray2HexStr(byteArr);
    }else{
        strText = CSettings::getInstance()->byteArray2Str(byteArr);
    }
    //时间戳
    if(ui->pushButton_timestamp->isChecked())
        strText = timestamp() + strText;

    //设置文本样式 追加 显示
    QTextCharFormat textFmt;
    textFmt.setFontItalic(false);
    textFmt.setForeground(QColor("black"));

    ui->textEdit_receive->mergeCurrentCharFormat(textFmt);
    ui->textEdit_receive->append(strText);
    ui->textEdit_receive->setAlignment(Qt::AlignLeft);
    ui->textEdit_receive->moveCursor(QTextCursor::End);


    strText = CSettings::getInstance()->byteArray2Str(byteArr);
    if(strstr(strText.toStdString().c_str(),"\r\n")!=NULL){
        m_nIterm = strText.split(",").size();
        if(m_nIterm!=m_nItermlast)
        {
            qDebug()<<"emit itermchanged";
            m_nItermlast = m_nIterm;
            emit itermchanged(m_nIterm);
        }
        addRandomGraph(strText.remove("\r\n"));
    }
    else
    {
        return ;
    }
}

QString VReceive::timestamp()
{
    return "[" + QTime::currentTime().toString() + "]  ";
}

void VReceive::on_pushButton_clear_clicked()
{
    // qDebug()<<"清除按钮按下";
    ui->textEdit_receive->clear();
}

void VReceive::on_tabWidget_currentChanged(int index)
{
    // qDebug()<<index;
    if(index == 1)
    {
        // qDebug()<<index;
    }
}



void VReceive::titleDoubleClick(QMouseEvent* event)
{
    Q_UNUSED(event)
    if (QCPTextElement *title = qobject_cast<QCPTextElement*>(sender()))
    {
        // Set the plot title by double clicking on it
        bool ok;
        QString newTitle = QInputDialog::getText(this, "QCustomPlot example", "New plot title:", QLineEdit::Normal, title->text(), &ok);
        if (ok)
        {
            title->setText(newTitle);
            ui->customPlot->replot();
            qDebug()<<"titleDoubleClick replot";
        }
    }
}

void VReceive::axisLabelDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part)
{
    // Set an axis label by double clicking on it
    if (part == QCPAxis::spAxisLabel) // only react when the actual axis label is clicked, not tick label or axis backbone
    {
        bool ok;
        QString newLabel = QInputDialog::getText(this, "QCustomPlot example", "New axis label:", QLineEdit::Normal, axis->label(), &ok);
        if (ok)
        {
            axis->setLabel(newLabel);
            ui->customPlot->replot();
            qDebug()<<"axisLabelDoubleClick replot";
        }
    }
}

void VReceive::legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item)
{
    // Rename a graph by double clicking on its legend item
    Q_UNUSED(legend)
    if (item) // only react if item was clicked (user could have clicked on border padding of legend where there is no item, then item is 0)
    {
        QCPPlottableLegendItem *plItem = qobject_cast<QCPPlottableLegendItem*>(item);
        bool ok;
        QString newName = QInputDialog::getText(this, "QCustomPlot example", "New graph name:", QLineEdit::Normal, plItem->plottable()->name(), &ok);
        if (ok)
        {
            plItem->plottable()->setName(newName);
            ui->customPlot->replot();
            qDebug()<<"legendDoubleClick replot";
        }
    }
}

void VReceive::selectionChanged()
{
    /*
   normally, axis base line, axis tick labels and axis labels are selectable separately, but we want
   the user only to be able to select the axis as a whole, so we tie the selected states of the tick labels
   and the axis base line together. However, the axis label shall be selectable individually.

   The selection state of the left and right axes shall be synchronized as well as the state of the
   bottom and top axes.

   Further, we want to synchronize the selection of the graphs with the selection state of the respective
   legend item belonging to that graph. So the user can select a graph by either clicking on the graph itself
   or on its legend item.
  */

    // make top and bottom axes be selected synchronously, and handle axis and tick labels as one selectable object:
    if (ui->customPlot->xAxis->selectedParts().testFlag(QCPAxis::spAxis) || ui->customPlot->xAxis->selectedParts().testFlag(QCPAxis::spTickLabels) ||
        ui->customPlot->xAxis2->selectedParts().testFlag(QCPAxis::spAxis) || ui->customPlot->xAxis2->selectedParts().testFlag(QCPAxis::spTickLabels))
    {
        ui->customPlot->xAxis2->setSelectedParts(QCPAxis::spAxis|QCPAxis::spTickLabels);
        ui->customPlot->xAxis->setSelectedParts(QCPAxis::spAxis|QCPAxis::spTickLabels);
    }
    // make left and right axes be selected synchronously, and handle axis and tick labels as one selectable object:
    if (ui->customPlot->yAxis->selectedParts().testFlag(QCPAxis::spAxis) || ui->customPlot->yAxis->selectedParts().testFlag(QCPAxis::spTickLabels) ||
        ui->customPlot->yAxis2->selectedParts().testFlag(QCPAxis::spAxis) || ui->customPlot->yAxis2->selectedParts().testFlag(QCPAxis::spTickLabels))
    {
        ui->customPlot->yAxis2->setSelectedParts(QCPAxis::spAxis|QCPAxis::spTickLabels);
        ui->customPlot->yAxis->setSelectedParts(QCPAxis::spAxis|QCPAxis::spTickLabels);
    }

    // synchronize selection of graphs with selection of corresponding legend items:
    for (int i=0; i<ui->customPlot->graphCount(); ++i)
    {
        QCPGraph *graph = ui->customPlot->graph(i);
        QCPPlottableLegendItem *item = ui->customPlot->legend->itemWithPlottable(graph);
        if (item->selected() || graph->selected())
        {
            item->setSelected(true);
            graph->setSelection(QCPDataSelection(graph->data()->dataRange()));
        }
    }
}

void VReceive::mousePress()
{
    // if an axis is selected, only allow the direction of that axis to be dragged
    // if no axis is selected, both directions may be dragged

    if (ui->customPlot->xAxis->selectedParts().testFlag(QCPAxis::spAxis))
        ui->customPlot->axisRect()->setRangeDrag(ui->customPlot->xAxis->orientation());
    else if (ui->customPlot->yAxis->selectedParts().testFlag(QCPAxis::spAxis))
        ui->customPlot->axisRect()->setRangeDrag(ui->customPlot->yAxis->orientation());
    else
        ui->customPlot->axisRect()->setRangeDrag(Qt::Horizontal|Qt::Vertical);
}

void VReceive::mouseWheel()
{
    // if an axis is selected, only allow the direction of that axis to be zoomed
    // if no axis is selected, both directions may be zoomed

    if (ui->customPlot->xAxis->selectedParts().testFlag(QCPAxis::spAxis))
    {

        qDebug()<<"xAxis";
        ui->customPlot->axisRect()->setRangeZoom(ui->customPlot->xAxis->orientation());
    }
    else if (ui->customPlot->yAxis->selectedParts().testFlag(QCPAxis::spAxis))
    {
        qDebug()<<"yAxis";
        ui->customPlot->axisRect()->setRangeZoom(ui->customPlot->yAxis->orientation());
    }
    else
    {
        qDebug()<<"xy";
        ui->customPlot->axisRect()->setRangeZoom(Qt::Horizontal|Qt::Vertical);
    }
}


void VReceive::itermchange(int nIterm)
{
    qDebug()<<"changed "<<nIterm;
    temp=0;
    // 清空 yData 数组中的所有元素
    for (int i = 0; i < 512; ++i) {
        yData[i].clear();
    }

    // 清空 xData 中的所有元素
    xData.clear();

    ui->customPlot->clearGraphs();
    ui->customPlot->clearPlottables();
    ui->customPlot->clearItems();
    for (int i = 0; i < nIterm; ++i) {
        ui->customPlot->addGraph();
        ui->customPlot->graph(i)->setName(QString("New graph %1").arg(ui->customPlot->graphCount()-1));

        ui->customPlot->graph(i)->setLineStyle((QCPGraph::LineStyle)(1));
        if (std::rand()%100 > 50)
            ui->customPlot->graph(i)->setScatterStyle(QCPScatterStyle((QCPScatterStyle::ScatterShape)(1)));
        QPen graphPen;
        graphPen.setColor(QColor(std::rand()%245+10, std::rand()%245+10, std::rand()%245+10));
        graphPen.setWidthF(std::rand()/(double)RAND_MAX*2+1);

        ui->customPlot->graph(i)->setPen(graphPen);

        ui->customPlot->replot();
        qDebug()<<"itermchange replot";
    }

}


void VReceive::addRandomGraph(const QString &data)
{
    // qDebug() << "addRandomGraph data:"<<data;
    QStringList dataList = data.split(",");
    if (dataList.size() < 1)
    {
        // qDebug() << "无数据";
        return;
    }
    // qDebug() << "data:"<<dataList;
    int dataSize = dataList.size();
    // qDebug() << "dataSize:"<<dataSize;
    xData.append(temp);
    temp++;
    for (int i = 0; i < dataSize; ++i)
    {
        yData[i].append(dataList[i].toDouble());
    }

    for (int i = 0; i < dataSize; ++i)
    {
        // qDebug() << "X:"<<xData <<"Y"<< yData[i];
        ui->customPlot->graph(i)->setData(xData, yData[i]);
    }

    ui->customPlot->replot();
    qDebug()<<"addRandomGraph replot";
    ui->customPlot->rescaleAxes();
}

void VReceive::removeSelectedGraph()
{
    if (ui->customPlot->selectedGraphs().size() > 0)
    {
        ui->customPlot->removeGraph(ui->customPlot->selectedGraphs().first());
        ui->customPlot->replot();
    }
}

void VReceive::removeAllGraphs()
{
    ui->customPlot->clearGraphs();
    ui->customPlot->replot();
    qDebug()<<"removeAllGraphs replot";
}

void VReceive::contextMenuRequest(QPoint pos)
{
    QMenu *menu = new QMenu(this);
    menu->setAttribute(Qt::WA_DeleteOnClose);

    if (ui->customPlot->legend->selectTest(pos, false) >= 0) // context menu on legend requested
    {
        menu->addAction("Move to top left", this, SLOT(moveLegend()))->setData((int)(Qt::AlignTop|Qt::AlignLeft));
        menu->addAction("Move to top center", this, SLOT(moveLegend()))->setData((int)(Qt::AlignTop|Qt::AlignHCenter));
        menu->addAction("Move to top right", this, SLOT(moveLegend()))->setData((int)(Qt::AlignTop|Qt::AlignRight));
        menu->addAction("Move to bottom right", this, SLOT(moveLegend()))->setData((int)(Qt::AlignBottom|Qt::AlignRight));
        menu->addAction("Move to bottom left", this, SLOT(moveLegend()))->setData((int)(Qt::AlignBottom|Qt::AlignLeft));
    } else  // general context menu on graphs requested
    {
        menu->addAction("Add random graph", this, SLOT(addRandomGraph()));
        if (ui->customPlot->selectedGraphs().size() > 0)
            menu->addAction("Remove selected graph", this, SLOT(removeSelectedGraph()));
        if (ui->customPlot->graphCount() > 0)
            menu->addAction("Remove all graphs", this, SLOT(removeAllGraphs()));
    }

    menu->popup(ui->customPlot->mapToGlobal(pos));
}

void VReceive::moveLegend()
{
    if (QAction* contextAction = qobject_cast<QAction*>(sender())) // make sure this slot is really called by a context menu action, so it carries the data we need
    {
        bool ok;
        int dataInt = contextAction->data().toInt(&ok);
        if (ok)
        {
            ui->customPlot->axisRect()->insetLayout()->setInsetAlignment(0, (Qt::Alignment)dataInt);
            ui->customPlot->replot();
            qDebug()<<"moveLegend replot";
        }
    }
}


void VReceive::twoPointZoom(const QPointF &pos1, const QPointF &pos2) {
    // Convert screen coordinates to plot coordinates
    double x1 = ui->customPlot->xAxis->pixelToCoord(pos1.x());
    double x2 = ui->customPlot->xAxis->pixelToCoord(pos2.x());
    double y1 = ui->customPlot->yAxis->pixelToCoord(pos1.y());
    double y2 = ui->customPlot->yAxis->pixelToCoord(pos2.y());

    // Calculate the new range
    double minX = qMin(x1, x2);
    double maxX = qMax(x1, x2);
    double minY = qMin(y1, y2);
    double maxY = qMax(y1, y2);
    QCPRange xRange(minX, maxX);
    QCPRange yRange(minY, maxY);

    // Zoom in x direction if x-axis selected, y direction if y-axis selected, both if none selected
    if (ui->customPlot->xAxis->selectedParts().testFlag(QCPAxis::spAxis)) {
        ui->customPlot->xAxis->setRange(xRange);
    } else if (ui->customPlot->yAxis->selectedParts().testFlag(QCPAxis::spAxis)) {
        ui->customPlot->yAxis->setRange(yRange);
    } else {
        ui->customPlot->xAxis->setRange(xRange);
        ui->customPlot->yAxis->setRange(yRange);
    }
}


bool VReceive::eventFilter(QObject *obj, QEvent *event) {
    // Check if the event is a touch event
    if (event->type() == QEvent::TouchUpdate) {
        QTouchEvent *touchEvent = static_cast<QTouchEvent*>(event);

        // Check if there are at least two touch points
        if (touchEvent->touchPoints().size() < 2)
            return false;

        // Retrieve touch points
        QPointF pos1, pos2;
        int touchCount = 0;
        for (const QTouchEvent::TouchPoint &touchPoint : touchEvent->touchPoints()) {
            if (touchPoint.state() == Qt::TouchPointPressed) {
                if (touchCount == 0)
                    pos1 = touchPoint.pos();
                else if (touchCount == 1)
                    pos2 = touchPoint.pos();
                touchCount++;
            }
        }

        // Ensure there are exactly two touch points
        if (touchCount != 2)
            return false;

        // Perform two-point zoom
        twoPointZoom(pos1, pos2);
        return true; // Event handled
    }

    return QObject::eventFilter(obj, event);
}
